package me.leiusual.sharing.pref

import android.content.Context
import android.content.pm.PackageManager
import me.leiusual.sharing.pref.impl.KDelegate
import me.leiusual.sharing.util.extension.toAny
import me.leiusual.sharing.util.extension.toJson
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton

/**
 * author: leiusual
 * create on: 2019-08-10
 * description:
 */
@Singleton
class Store @Inject constructor(
    context: Context
) : AbstractPref(context) {

  val bindingStoreId by lazy {
    try {
      val info = context.packageManager.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
      info.metaData.getInt("bindingStoreId").toLong()
    } catch (e: Exception) {
      Timber.w(e)
      0L
    }
  }

  // 全部店铺列表
  private var _storeList: String? by KDelegate.KString(sp)
  var storeList: Map<Long, String>
    get() {
      return _storeList.toAny<Map<Long, String>>() ?: emptyMap()
    }
    set(value) {
      _storeList = value.toJson()
    }

  // 可管理店铺列表
  private var _managedStoreList: String? by KDelegate.KString(sp)
  var managedStoreList: Map<Long, String>
    get() {
      return _managedStoreList.toAny<Map<Long, String>>() ?: emptyMap()
    }
    set(value) {
      _managedStoreList = value.toJson()
    }

  // 当前选中的店铺id
  var currentStoreId: Long by KDelegate.KLong(sp, bindingStoreId)
}